﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Networking.BackgroundTransfer;
using Windows.Storage;
using Windows.System.Display;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Web;

// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234238 上有介绍

namespace LikeBangumi.Pages
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class DownloadPage : Page
    {
        public DownloadPage()
        {
            this.InitializeComponent();
        }
        public delegate void PlayVideo(PlayModel model);
        public event PlayVideo playEvent;

        private void btn_Home_Click(object sender, RoutedEventArgs e)
        {
            pivot.SelectedIndex = Convert.ToInt32((sender as Button).Tag);
        }

        private void pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UpdateUI();
            SolidColorBrush color = new SolidColorBrush(new Windows.UI.Color() { A = 255, B = 216, G = 123, R = 30 });
            switch (pivot.SelectedIndex)
            {
                case 0:
                    btn_Home.BorderBrush = color;
                    break;
                case 1:
                    btn_Tag.BorderBrush = color;
                    break;
                default:
                    break;
            }
        }

        private void UpdateUI()
        {
            SolidColorBrush color = new SolidColorBrush(new Windows.UI.Color() { A = 0, B = 0, G = 0, R = 0 });
            btn_Home.BorderBrush = color;
            btn_Tag.BorderBrush = color;
        }

        List<DownHelper.HandleModel> downlingModel = new List<DownHelper.HandleModel>();
        List<string> HandleList = new List<string>();
        SettingHelper settings = new SettingHelper();
        //跳转，开始监视，需要判断是否已经监视，否则会出现N个通知
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            //messShow.Show("Tips：如果下载完成后应用不显示，请点击已完成右下角的'导入已完成'", 5000);
            // bg.Color = ((SolidColorBrush)this.Frame.Tag).Color;
            pr_Load.Visibility = Visibility.Collapsed;
            if (e.Parameter != null)
            {
                pivot.SelectedIndex = (int)e.Parameter;
            }
            try
            {
                //if (settings.SettingContains("HoldLight"))
                //{
                //    tw_Light.IsChecked = (bool)settings.GetSettingValue("HoldLight");
                //}
                //else
                //{
                //    tw_Light.IsChecked = false;
                //}

                List_Down.Items.Clear();
                downlingModel.Clear();
                IReadOnlyList<DownloadOperation> downloads = null;
                GetDownOk_New();
                // 获取所有后台下载任务
                downloads = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(DownHelper.DownModel.group);
                if (downloads.Count > 0)
                {
                    foreach (var item in downloads)
                    {
                        //ls.Add(item.Guid);
                        List_Down.Items.Add(new DownHelper.HandleModel()
                        {
                            downOp = item,
                            Size = item.Progress.BytesReceived.ToString(),
                            downModel = await GetInfo(item.Guid.ToString())
                        });
                    }
                    //list.ItemsSource = downlingModel;
                }
                if (downloads.Count > 0)
                {
                    List<Task> tasks = new List<Task>();
                    foreach (DownHelper.HandleModel model in List_Down.Items)
                    {
                        //bool test = HandleList.Contains(model.downOp.Guid.ToString());
                        if (!HandleList.Contains(model.downOp.Guid.ToString()))
                        {
                            // 监视指定的后台下载任务
                            HandleList.Add(model.downOp.Guid.ToString());
                            tasks.Add(HandleDownloadAsync(model));
                        }
                    }
                    await Task.WhenAll(tasks);
                }
            }
            catch (Exception)
            {
            }
        }

        //读取文件
        private async Task<DownHelper.DownModel> GetInfo(string guid)
        {
            // StorageFolder folder = ApplicationData.Current.LocalFolder;
            StorageFolder DowFolder = await KnownFolders.VideosLibrary.CreateFolderAsync("ZF-Down", CreationCollisionOption.OpenIfExists);
            StorageFile file = await DowFolder.GetFileAsync(guid + ".bili");
            //用Url编码是因为不支持读取中文名
            //含会出现：在多字节的目标代码页中，没有此 Unicode 字符可以映射到的字符。错误
            string path = WebUtility.UrlDecode(await FileIO.ReadTextAsync(file)) + @"\" + guid + ".json";
            StorageFile files = await StorageFile.GetFileFromPathAsync(path);
            string json = await FileIO.ReadTextAsync(files);
            return JsonConvert.DeserializeObject<DownHelper.DownModel>(json);
        }

        private async void GetDownOk_New()
        {
            try
            {
               list_Downed.ItemsSource = null;
                //DownHelper.Downloaded.Clear();
                await Task.Run(async () =>
                {
                    StorageFolder DownFolder = await KnownFolders.VideosLibrary.CreateFolderAsync("ZF-Down", CreationCollisionOption.OpenIfExists);
                    List<DownHelper.FolderModel> list = new List<DownHelper.FolderModel>();
                    foreach (var item in await DownFolder.GetFoldersAsync())
                    {
                        DownHelper.FolderModel model = new DownHelper.FolderModel()
                        {
                            title = item.Name,
                            count = 0,
                            downedCount = 0,
                        };
                        List<DownHelper.DownModel> list_file = new List<DownHelper.DownModel>();
                        foreach (var item1 in await item.GetFoldersAsync())
                        {
                            foreach (var item2 in await item1.GetFilesAsync())
                            {
                                if (item2.FileType == ".json")
                                {
                                    StorageFile files = item2;
                                    string json = await FileIO.ReadTextAsync(item2);
                                    DownHelper.DownModel model123 = JsonConvert.DeserializeObject<DownHelper.DownModel>(json);
                                    if (model123.downloaded == true)
                                    {
                                        list_file.Add(model123);
                                        model.downedCount++;
                                        //DownHelper.Downloaded.Add(model123.mid);
                                    }
                                    model.IsBangumi = model123.isBangumi;
                                    model.aid = model123.aid;
                                }
                            }
                            model.count++;
                        }
                        model.path = item.Path;
                        model.downModel = list_file;
                        list.Add(model);
                    }
                    await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { list_Downed.ItemsSource = list; });
                });
            }
            catch (Exception)
            {
            }

        }
        /// <summary>
        /// 监视指定的后台下载任务
        /// </summary>
        /// <param name="download">后台下载任务</param>
        private async Task HandleDownloadAsync(DownHelper.HandleModel model)
        {
            try
            {
                DownloadProgress(model.downOp);
                //进度监控
                Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);
                await model.downOp.AttachAsync().AsTask(model.cts.Token, progressCallback);

                //保存任务信息
                //  StorageFolder folder = ApplicationData.Current.LocalFolder;
                StorageFolder DowFolder = await KnownFolders.VideosLibrary.CreateFolderAsync("ZF-Down", CreationCollisionOption.OpenIfExists);
                StorageFile file = await DowFolder.GetFileAsync(model.Guid + ".bili");
                //用Url编码是因为不支持读取中文名
                //含会出现：在多字节的目标代码页中，没有此 Unicode 字符可以映射到的字符。错误
                string path = WebUtility.UrlDecode(await FileIO.ReadTextAsync(file));
                StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(path);
                StorageFile files = await folder.CreateFileAsync(model.Guid + ".json", CreationCollisionOption.OpenIfExists); //await StorageFile.GetFileFromPathAsync(path+@"\" + model.Guid + ".json");
                string json = await FileIO.ReadTextAsync(files);
                DownHelper.DownModel info = JsonConvert.DeserializeObject<DownHelper.DownModel>(json);
                info.downloaded = true;
                string jsonInfo = JsonConvert.SerializeObject(info);
                StorageFile fileWrite = await folder.CreateFileAsync(info.Guid + ".json", CreationCollisionOption.ReplaceExisting);
                await FileIO.WriteTextAsync(fileWrite, jsonInfo);
                //移除正在监控
                HandleList.Remove(model.downModel.Guid);
                GetDownOk_New();
            }
            catch (TaskCanceledException)
            {
                //取消通知
                //ToastTemplateType toastTemplate = ToastTemplateType.ToastText01;
                //XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
                //XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");
                //IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
                //((XmlElement)toastNode).SetAttribute("duration", "short");
                //toastTextElements[0].AppendChild(toastXml.CreateTextNode(String.Format("取消任务{0}", model.downModel.title)));
                //ToastNotification toast = new ToastNotification(toastXml);
                //ToastNotificationManager.CreateToastNotifier().Show(toast);
            }
            catch (Exception ex)
            {
                WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);
                return;
            }
            finally
            {
                List_Down.Items.Remove(model);
            }
        }
        //进度发生变化时,通知更新UI
        private void DownloadProgress(DownloadOperation op)
        {
            try
            {
                DownHelper.HandleModel test = null;
                foreach (DownHelper.HandleModel item in List_Down.Items)
                {
                    if (item.downOp.Guid == op.Guid)
                    {
                        test = item;
                    }
                }
                if (List_Down.Items.Contains(test))
                {
                    ((DownHelper.HandleModel)List_Down.Items[List_Down.Items.IndexOf(test)]).Size = op.Progress.BytesReceived.ToString();
                    ((DownHelper.HandleModel)List_Down.Items[List_Down.Items.IndexOf(test)]).Status = op.Progress.Status.ToString();
                    ((DownHelper.HandleModel)List_Down.Items[List_Down.Items.IndexOf(test)]).Progress = ((double)op.Progress.BytesReceived / op.Progress.TotalBytesToReceive) * 100;
                }
            }
            catch (Exception)
            {
                return;
            }

        }

        private void btn_Pause_Click(object sender, RoutedEventArgs e)
        {
            ((sender as AppBarButton).DataContext as DownHelper.HandleModel).downOp.Pause();
           
        }

        private void btn_Download_Click(object sender, RoutedEventArgs e)
        {
            var ss = ((sender as AppBarButton).DataContext as DownHelper.HandleModel);
            if (ss.downOp.Progress.Status == BackgroundTransferStatus.PausedByApplication)
            {
                ss.downOp.Resume();
            }
        }
        private async void btn_Canacel_Click(object sender, RoutedEventArgs e)
        {
            var ss = ((sender as AppBarButton).DataContext as DownHelper.HandleModel);
            ss.cts.Cancel(false);
            ss.cts.Dispose();
            try
            {

                StorageFolder DowFolder = await KnownFolders.VideosLibrary.CreateFolderAsync("ZF-Down", CreationCollisionOption.OpenIfExists);
                StorageFile file = await DowFolder.GetFileAsync(ss.Guid + ".bili");
                //用Url编码是因为不支持读取中文名
                //含会出现：在多字节的目标代码页中，没有此 Unicode 字符可以映射到的字符。错误
                string path = WebUtility.UrlDecode(await FileIO.ReadTextAsync(file));
                StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(path);
                await folder.DeleteAsync(StorageDeleteOption.Default);
                await file.DeleteAsync(StorageDeleteOption.Default);
            }
            catch (Exception)
            {
                //throw;
            }
        }

        private void btn_Select_Checked(object sender, RoutedEventArgs e)
        {
            list_Downed.IsItemClickEnabled = false;
            list_Downed.SelectionMode = ListViewSelectionMode.Multiple;
        }

        private void btn_Select_Unchecked(object sender, RoutedEventArgs e)
        {
            list_Downed.IsItemClickEnabled = true;
            list_Downed.SelectionMode = ListViewSelectionMode.None;
        }

        private async void btn_Delete_Folder_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                foreach (DownHelper.FolderModel item in list_Downed.SelectedItems)
                {
                    StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(item.path);

                    await folder.DeleteAsync(StorageDeleteOption.Default);
                }
                await new MessageDialog("成功删除！").ShowAsync();
            }
            catch (Exception ex)
            {
                await new MessageDialog("删除时发生错误\r\n" + ex.Message).ShowAsync();
            }
            finally
            {
                GetDownOk_New();
            }
        }

        private void btn_Input_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btn_Refresh_Click(object sender, RoutedEventArgs e)
        {
            GetDownOk_New();
        }

        private void list_Downed_ItemClick(object sender, ItemClickEventArgs e)
        {
            sp_Video.IsPaneOpen = true;
            DownHelper.FolderModel folder = (e.ClickedItem as DownHelper.FolderModel);
            txt_Title.Tag = folder.IsBangumi;
            btn_Go.Tag = folder.aid;
            txt_Title.Text = folder.title;//+ "(" + folder.aid + ")";
            list_DownOk_View.ItemsSource = folder.downModel;
        }

        private void btn_Go_Click(object sender, RoutedEventArgs e)
        {
           
        }

        private void cb_btn_Select_Unchecked(object sender, RoutedEventArgs e)
        {
            list_DownOk_View.IsItemClickEnabled = true;
            list_DownOk_View.SelectionMode = ListViewSelectionMode.None;
        }

        private async void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                foreach (DownHelper.DownModel item in list_DownOk_View.SelectedItems)
                {
                    StorageFolder folder = await(await StorageFile.GetFileFromPathAsync(item.path)).GetParentAsync();
                    StorageFile file = await(await KnownFolders.VideosLibrary.CreateFolderAsync("Bili-Down", CreationCollisionOption.OpenIfExists)).CreateFileAsync(item.Guid + ".bili", CreationCollisionOption.OpenIfExists);
                    await folder.DeleteAsync(StorageDeleteOption.Default);
                    await file.DeleteAsync(StorageDeleteOption.Default);
                }
                await new MessageDialog("成功删除！").ShowAsync();
            }
            catch (Exception ex)
            {
                await new MessageDialog("删除时发生错误\r\n" + ex.Message).ShowAsync();
            }
            finally
            {
                GetDownOk_New();
                sp_Video.IsPaneOpen = false;
            }
        }

        private void cb_btn_Select_Checked(object sender, RoutedEventArgs e)
        {
            list_DownOk_View.IsItemClickEnabled = false;
            list_DownOk_View.SelectionMode = ListViewSelectionMode.Multiple;
        }

        private void list_DownOk_View_ItemClick(object sender, ItemClickEventArgs e)
        {
            var s = e.ClickedItem as DownHelper.DownModel;
            playEvent(new PlayModel() { info = s.path, type = BangumiType.Local });
            sp_Video.IsPaneOpen = false;
        }

        private void btn_Light_Unchecked(object sender, RoutedEventArgs e)
        {
            if (dispRequest != null)
            {
                dispRequest = null;
            }
            settings.SetSettingValue("HoldLight", btn_Light.IsChecked.Value);
        }
        DisplayRequest dispRequest;
        private void btn_Light_Checked(object sender, RoutedEventArgs e)
        {
            if (dispRequest == null)
            {
                // 用户观看视频，需要保持屏幕的点亮状态
                dispRequest = new DisplayRequest();
                dispRequest.RequestActive(); // 激活显示请求
            }
            settings.SetSettingValue("HoldLight", btn_Light.IsChecked.Value);
        }


    }
}
